package com.it.schoolhomeos.service.impl;

import com.it.schoolhomeos.entity.Attendance;
import com.it.schoolhomeos.entity.ClassInfo;
import com.it.schoolhomeos.entity.Grade;
import com.it.schoolhomeos.entity.Student;
import com.it.schoolhomeos.entity.User;
import com.it.schoolhomeos.repository.AttendanceRepository;
import com.it.schoolhomeos.repository.ClassInfoRepository;
import com.it.schoolhomeos.repository.GradeRepository;
import com.it.schoolhomeos.repository.StudentRepository;
import com.it.schoolhomeos.repository.UserRepository;
import com.it.schoolhomeos.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * StudentService接口的实现类
 * 
 * 实现学生相关的业务逻辑
 */
@Service
@Transactional
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;
    
    @Autowired
    private ClassInfoRepository classInfoRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private GradeRepository gradeRepository;
    
    @Autowired
    private AttendanceRepository attendanceRepository;
    
    /**
     * 获取学生列表
     * 
     * @param classId 班级ID，可为null
     * @param parentId 家长ID，可为null
     * @param page 页码
     * @param size 每页大小
     * @return 分页的学生列表
     */
    @Override
    public Page<Student> getStudents(Long classId, Long parentId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("name"));
        
        // 根据条件查询
        if (classId != null && parentId != null) {
            Optional<ClassInfo> classInfoOpt = classInfoRepository.findById(classId);
            Optional<User> parentOpt = userRepository.findById(parentId);
            if (classInfoOpt.isPresent() && parentOpt.isPresent()) {
                return studentRepository.findByClassInfoAndParent(classInfoOpt.get(), parentOpt.get(), pageable);
            }
        } else if (classId != null) {
            Optional<ClassInfo> classInfoOpt = classInfoRepository.findById(classId);
            if (classInfoOpt.isPresent()) {
                return studentRepository.findByClassInfo(classInfoOpt.get(), pageable);
            }
        } else if (parentId != null) {
            Optional<User> parentOpt = userRepository.findById(parentId);
            if (parentOpt.isPresent()) {
                return studentRepository.findByParent(parentOpt.get(), pageable);
            }
        }
        
        // 如果没有条件，返回所有学生
        return studentRepository.findAll(pageable);
    }
    
    /**
     * 获取学生列表，支持关键字搜索
     * 
     * @param classId 班级ID，可为null
     * @param parentId 家长ID，可为null
     * @param keyword 搜索关键字，可为null
     * @param page 页码
     * @param size 每页大小
     * @return 分页的学生列表
     */
    @Override
    public Page<Student> getStudents(Long classId, Long parentId, String keyword, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("name"));
        
        // 记录日志，便于调试
        System.out.println("搜索学生 - 班级ID: " + classId + ", 家长ID: " + parentId + ", 关键字: " + keyword);
        
        // 如果关键字为空，则调用无关键字的方法
        if (keyword == null || keyword.trim().isEmpty()) {
            return getStudents(classId, parentId, page, size);
        }
        
        // 根据条件查询
        if (classId != null && parentId != null) {
            Optional<ClassInfo> classInfoOpt = classInfoRepository.findById(classId);
            Optional<User> parentOpt = userRepository.findById(parentId);
            if (classInfoOpt.isPresent() && parentOpt.isPresent()) {
                return studentRepository.findByClassInfoAndParentAndKeyword(
                    classInfoOpt.get(), parentOpt.get(), keyword, pageable);
            }
        } else if (classId != null) {
            Optional<ClassInfo> classInfoOpt = classInfoRepository.findById(classId);
            if (classInfoOpt.isPresent()) {
                return studentRepository.findByClassInfoAndKeyword(classInfoOpt.get(), keyword, pageable);
            }
        } else if (parentId != null) {
            Optional<User> parentOpt = userRepository.findById(parentId);
            if (parentOpt.isPresent()) {
                return studentRepository.findByParentAndKeyword(parentOpt.get(), keyword, pageable);
            }
        }
        
        // 如果只有关键字，返回按关键字搜索的结果
        return studentRepository.findByKeyword(keyword, pageable);
    }
    
    /**
     * 根据ID获取学生详情
     * 
     * @param id 学生ID
     * @return 学生对象
     * @throws RuntimeException 如果学生不存在
     */
    @Override
    public Student getStudentById(Long id) {
        return studentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("学生不存在"));
    }
    
    /**
     * 创建新学生
     * 
     * @param student 学生对象
     * @return 创建成功的学生对象
     */
    @Override
    public Student createStudent(Student student) {
        // 设置创建时间
        student.setCreateTime(LocalDateTime.now());
        
        // 保存学生
        return studentRepository.save(student);
    }
    
    /**
     * 更新学生信息
     * 
     * @param student 学生对象
     * @return 更新后的学生对象
     * @throws RuntimeException 如果学生不存在
     */
    @Override
    public Student updateStudent(Student student) {
        // 检查学生是否存在
        if (!studentRepository.existsById(student.getId())) {
            throw new RuntimeException("学生不存在");
        }
        
        // 设置更新时间
        student.setUpdateTime(LocalDateTime.now());
        
        // 保存学生
        return studentRepository.save(student);
    }
    
    /**
     * 删除学生
     * 
     * @param id 学生ID
     * @throws RuntimeException 如果学生不存在
     */
    @Override
    public void deleteStudent(Long id) {
        // 检查学生是否存在
        if (!studentRepository.existsById(id)) {
            throw new RuntimeException("学生不存在");
        }
        
        // 删除学生
        studentRepository.deleteById(id);
    }

    @Override
    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    @Override
    public Student findById(Long id) {
        return studentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("学生不存在: " + id));
    }

    @Override
    public Student save(Student student) {
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        student.setCreateTime(now);
        student.setUpdateTime(now);
        return studentRepository.save(student);
    }

    @Override
    public Student update(Student student) {
        if (!studentRepository.existsById(student.getId())) {
            throw new RuntimeException("学生不存在: " + student.getId());
        }
        return studentRepository.save(student);
    }

    @Override
    public void deleteById(Long id) {
        if (!studentRepository.existsById(id)) {
            throw new RuntimeException("学生不存在: " + id);
        }
        
        try {
            // 1. 先删除学生的成绩记录
            List<Grade> grades = gradeRepository.findByStudentId(id);
            if (grades != null && !grades.isEmpty()) {
                gradeRepository.deleteAll(grades);
            }
            
            // 2. 删除学生的考勤记录
            List<Attendance> attendances = attendanceRepository.findByStudentId(id);
            if (attendances != null && !attendances.isEmpty()) {
                attendanceRepository.deleteAll(attendances);
            }
            
            // 3. 如果有其他关联表，也需要在这里处理
            
            // 4. 最后删除学生
            studentRepository.deleteById(id);
        } catch (Exception e) {
            throw new RuntimeException("删除学生失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<Student> findByCurrentParent() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        return studentRepository.findByParentUsername(username);
    }

    @Override
    public Student findByIdAndCurrentParent(Long id) {
        // 获取当前登录用户（家长）
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User parent = userRepository.findByUsername(username).orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 查找指定ID的学生，并确保该学生属于当前家长
        return studentRepository.findByIdAndParentId(id, parent.getId())
                .orElseThrow(() -> new RuntimeException("学生不存在或无权访问"));
    }

    @Override
    public List<Student> findByCurrentTeacher() {
        // 获取当前登录用户（教师）
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User teacher = userRepository.findByUsername(username).orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 查找该教师所教的班级
        List<ClassInfo> classes = classInfoRepository.findByTeacherId(teacher.getId());
        
        // 如果教师没有班级，返回空列表
        if (classes.isEmpty()) {
            return List.of();
        }
        
        // 获取这些班级的所有学生
        return studentRepository.findByClassInfoIn(classes);
    }
} 